import BlackBoard.InputSim;
import pgm;
from subprocess import call;
import time, os;

#Wait-N-Meet PPT Example
# sStatesFile = "./BlackBoard/StateSpace";
# sTransFile = "./BlackBoard/transitionM";
# sPriorsFile = "./BlackBoard/priors";
#RunChase Example
# sStatesFile = "./BlackBoard/StateSpace2";
# sTransFile = "./BlackBoard/transitionM2";
# sPriorsFile = "./BlackBoard/priors2";
#UofA Video Example
sStatesFile = "./BlackBoard/StateSpace3";
sTransFile = "./BlackBoard/transitionM3";
sPriorsFile = "./BlackBoard/priors3";

inputSim = BlackBoard.InputSim(pgm, sStatesFile, sTransFile, sPriorsFile);
blackB = BlackBoard.BlackBoard(inputSim);

#UofA Video Example
# blackB.addXmlActs_ToBB("./BlackBoard/XmlActs/AllActs.xml");
aFolders, aFiles = [], [];
f = open("InputFolders", "r");
while 1:
    sFolder = f.readline().replace("\n","");
    if not(sFolder.startswith("#")):
        aFolders.append(sFolder);
    if not aFolders[-1]:
        if aFolders[-1]=="":
            del aFolders[-1];
        break;
f.close();
for folder in aFolders:
    aFiles.append(os.listdir(folder));
    aFiles[-1].sort();
    
nInitT = time.time();
for i,sFolder in enumerate(aFiles):
    for sFile in sFolder:
        sFilePath = aFolders[i]+"/"+sFile;
        print "Reading file: " + sFilePath;
        blackB.addXmlActs_ToBB(sFilePath);
print "Graph Creation Time:", time.time()-nInitT, "seconds.";

# # nInitT = time.time();
# # for i in range(18):
# #     print "Reading file: standstill" + str(i).zfill(3) + ".xml";
# #     blackB.addXmlActs_ToBB("./BlackBoard/XmlActs/outstandstill/standstill" + str(i).zfill(3) + ".xml");
# # for i in range(41):
# #     print "Reading file: loiter" + str(i).zfill(3) + ".xml";
# #     blackB.addXmlActs_ToBB("./BlackBoard/XmlActs/outloiter/loiter" + str(i).zfill(3) + ".xml");
# # for i in range(181):
# #     print "Reading file: walk" + str(i).zfill(3) + ".xml";
# #     blackB.addXmlActs_ToBB("./BlackBoard/XmlActs/outwalk/walk" + str(i).zfill(3) + ".xml");
# # print "Graph:", time.time()-nInitT;
# blackB.addXmlActs_ToBB("./BlackBoard/XmlActs/outstandstill/standstill000.xml");
# blackB.addXmlActs_ToBB("./BlackBoard/XmlActs/outstandstill/standstill001.xml");
# blackB.addXmlActs_ToBB("./BlackBoard/XmlActs/outwalk/walk000.xml");
# blackB.addXmlActs_ToBB("./BlackBoard/XmlActs/outwalk/walk001.xml");

#Testing PPT bigger Example
# blackB.addXmlActs_ToBB("./BlackBoard/XmlActs/ActsHmmTest_Small.xml");
# blackB.addXmlActs_ToBB("./BlackBoard/XmlActs/ActsHmmAll.xml");
# # blackB.addXmlActs_ToBB("./BlackBoard/XmlActs/ActsHmmTest_Small3.xml");


# aActSeq1 = ["300.15", "50.35", "50.60", "300.85", "300.100"];
# aActSeq2 = ["300.15", "300.35", "300.60", "300.85", "300.100"];
# aActSeq3 = ["300.15", "300.35", "800.60", "800.85", "300.100"];
# aActSeq4 = ["300.15", "50.35", "800.60", "300.85", "300.100"];
# aActSeqs = [aActSeq1, aActSeq2, aActSeq3, aActSeq4];
# print "getProbSeq:", blackB.getProbSeq(aActSeq1);
# print blackB.getMaxProbSeq(aActSeqs);
# print "StateProb:", blackB.getStateProb("60", [0,1,1,0,0]);

#print blackB.getMaxStProb("60");
# print blackB.getMaxProbSeq();
# # aActSeq = ["4.248", "4.398"];
# # aActSeq = ["4.248", "Null_person1.398"];
# # aActSeq = ["2.248", "Null_person1.398"];
# # aActSeq = ["Null_person1.248", "Null_person1.398"];
# # print "getProbSeq:", blackB.getProbSeq(aActSeq, bSmooth=False);
# blackB.getHmms(bSmooth=True);

#print "\nRemoving Nodes:";
#blackB.removeAct("00");
#blackB.removeAct("300");
#blackB.removeAct("300");
# blackB.removeAct("800");
# blackB.removeAct("300");
# blackB.removeAct("64");
# blackB.removeAct("58");

# blackB.makeUsrSegment(65);
# blackB.removeUsrSegment(65);


# #Print Posterior Probs for States at "t"
# aTimes = [15, 35, 60, 85, 100];
# print "\n---";
# for nT in aTimes:
#     [aNodes, aPosts, sT] = blackB.getStatePosts(nT, nT);
#     print "\n--State Posts of time:", sT;
#     for i,node in enumerate(aNodes):
#         print node.name+":", aPosts[i];

# # [aNodes, aPosts, sT] = blackB.getStatePosts(90, 100); #Run:34,34 Chase:80,80
# # print "\n--State Posts of time:", sT;
# # for i,node in enumerate(aNodes):
# #     print node.name+":", aPosts[i];
    
# # aActSeq1 = ["800.50", "800.90"];
# # aActSeq2 = ["50.50", "Null_A"];
# # nProbSeq1 = blackB.getProbSeq(aActSeq1);
# # nProbSeq2 = blackB.getProbSeq(aActSeq2);
# # print "---\ngetProbSeq1:", nProbSeq1;
# # print "getProbSeq2:", nProbSeq2;
# # 
# print blackB.getMaxProbSeq();
# # print "---\ngetProbSeq1:", nProbSeq1;


# # #Print Joint Probs for States at "t"
# # [aNodes, aPosts, sT] = blackB.getJointProb(15, 100);
# # print "\n---";
# # print "Joint of Nodes at time:", sT;
# # for node in aNodes:
# #     print node.name;
# # print "Joint States & Probs:"; 
# # for i,nP in enumerate(aPosts):
# #     print bin(i)[2:].zfill(len(aNodes))+", Prob:", nP;

# print "\nGraph Info:"
# blackB.printGraph();


# blackB.addXmlActs_ToBB("./BlackBoard/XmlActs/xml_BB_Tests/Case1/run000.xml");
# blackB.addXmlActs_ToBB("./BlackBoard/XmlActs/xml_BB_Tests/Case1/chase-first000.xml");
# blackB.addXmlActs_ToBB("./BlackBoard/XmlActs/xml_BB_Tests/Case1/chase-second000.xml");
# blackB.addXmlActs_ToBB("./BlackBoard/XmlActs/xml_BB_Tests/Case2/run000.xml");
# blackB.addXmlActs_ToBB("./BlackBoard/XmlActs/xml_BB_Tests/Case2/chase-first000.xml");
# blackB.addXmlActs_ToBB("./BlackBoard/XmlActs/xml_BB_Tests/Case2/chase-second000.xml");


# print "\nGraph Info:"
# blackB.printGraph();
nInitT = time.time();
f = open("./Output_BestPaths", "w");
#aBestPath = blackB.inferenceBB.getMAP();
aBestPath = blackB.inferenceBB.getViterbi();
# aBestPath = blackB.inferenceBB.getMaxProd_VE();
for bestPath in aBestPath:
    sLine = bestPath[0]+": "+str(bestPath[1]);
    f.write(sLine+"\n");
#     print sLine;
print "Best paths saved in file ./Output_BestPaths";
f.close();
print "MAP method Time:", time.time()-nInitT, "seconds.";
# blackB.getMaxProd_VE();
# bSmooth = True;
# print "\n\n";
# blackB.getHmms(bSmooth=bSmooth);

# aActSeq1 = ["Null_person1.248", "Null_person1.398"]; #Null, Null
# aActSeq2 = ["2.248", "Null_person1.398"]; #Run, Null
# aActSeq3 = ["4.248", "Null_person1.398"]; #Chase, Null
# aActSeq4 = ["4.248", "4.398"]; #Chase, Chase
# print "\nPath Probabilities:";
# print "1. Null, Null:", blackB.getProbSeq(aActSeq1, bSmooth=bSmooth);
# print "2. Run, Null:", blackB.getProbSeq(aActSeq2, bSmooth=bSmooth);
# print "3. Chase, Null:", blackB.getProbSeq(aActSeq3, bSmooth=bSmooth);
# print "4. Chase, Chase:", blackB.getProbSeq(aActSeq4, bSmooth=bSmooth);
# # 
# aNodes = [];
# print "\n\nPosteriors:";
# blackB.setMExObs();
# # blackB.setEvObs(248);
# # blackB.setEvObs(398);
# for i,sK in enumerate(blackB.aActs_Time):
#     for j in range(len(blackB.aActs_Time[sK])):
#         aNodes.append(blackB.aActs_Time[sK][j].rootAct);
#         print "-State:", blackB.aActs_Time[sK][j].rootAct.name;
#     print i+1, "Priors:", blackB.graph.priorprob(aNodes);
#     print ""+ str(len(blackB.aActs_Time)-i) +":", blackB.graph.postprob(aNodes),"\n";
#     aNodes = [];

blackB.graph.setup();
blackB.graph.write2dot(fname='./BlackBoard/DynBB-graph.dot');
call(['C:/Program Files (x86)/Graphviz2.30/bin/dot.exe', '-Tpdf', './BlackBoard/DynBB-graph.dot', '-o', './BlackBoard/DynBB-graph.pdf']);
# blackB.graph.write2dot(fname='./BlackBoard/DynBB-graph.dot');
# call(['dot', '-Tpdf', './BlackBoard/DynBB-graph.dot', '-o', './BlackBoard/DynBB-graph.pdf']);
# call(['evince', './BlackBoard/DynBB-graph.pdf']);
